<template>
  <el-container>
    <!--关系模型树-->
    <el-aside width="300px" class="content-left-list">
      <div class="ps-panel nav-left-menu" style="height: 100%">
        <div class="ps-panel-head">
          <i class="ps-panel-head-icon iconfont icon-guanxiwajue"></i>
          <span class="ps-panel-head-title">关系模型信息</span>
        </div>

        <div class="ps-panel-body">
          <el-tree
            :data="relationships"
            node-key="id"
            default-expand-all
            :expand-on-click-node="false"
            :props="{ label: 'label_name' }"
            @node-click="treeRelationshipClick"
          ></el-tree>
          <!--<el-menu :default-active="nodeTypes[0].node" class="el-menu-vertical">-->
          <!--<el-menu-item v-for="item of nodeTypes" :index="item.node" :key="item.node" @click="init(item.node)">{{item.node_name}}</el-menu-item>-->
          <!--</el-menu>-->
        </div>
      </div>
    </el-aside>

    <!--关系实例列表-->
    <el-main class="content-main">
      <div class="ps-panel nav-left-menu" style="height: 100%">
        <div class="ps-panel-head">
          <i class="ps-panel-head-icon iconfont icon-list"></i>
          <span class="ps-panel-head-title">关系列表</span>
          <span class="query">
            <el-button
              type="primary"
              size="mini"
              @click="addModelInstance"
              v-show="this.currRelationshipId > 0"
              >添加实例关系</el-button
            >
          </span>
        </div>

        <div class="ps-panel-body">
          <el-table
            :data="currRelationshipInstances"
            size="small"
            highlight-current-row
            stripe
            style="width: 100%; margin-bottom: 10px"
          >
            <el-table-column prop="id" label="序号"></el-table-column>
            <el-table-column prop="type" label="关系名称"></el-table-column>
            <el-table-column
              prop="start_node_data.名称"
              label="开始节点名称"
            ></el-table-column>
            <el-table-column
              prop="start_node_data.labels"
              label="开始节点类型"
            ></el-table-column>
            <el-table-column
              prop="end_node_data.名称"
              label="结束节点名称"
            ></el-table-column>
            <el-table-column
              prop="end_node_data.labels"
              label="结束节点类型"
            ></el-table-column>
            <el-table-column fixed="right" label="操作" width="150">
              <template slot-scope="scope">
                <el-button
                  type="text"
                  size="small"
                  @click="showOrEdit(scope.row)"
                  >编辑/查看</el-button
                >
                <el-popover
                  style="margin-left: 10px"
                  width="160"
                  trigger="manual"
                  :ref="'del_popover_' + scope.row.id"
                >
                  <p style="text-align: center; margin: 15px 0px">
                    确定删除吗？
                  </p>
                  <div style="text-align: center; margin: 0">
                    <el-button
                      size="mini"
                      @click="delPopoverClose('del_popover_' + scope.row.id)"
                    >
                      取消
                    </el-button>
                    <el-button
                      type="primary"
                      size="mini"
                      @click="delInstance(scope.row)"
                      >确定
                    </el-button>
                  </div>
                  <el-button
                    type="text"
                    slot="reference"
                    size="small"
                    @click="delPopoverShow('del_popover_' + scope.row.id)"
                    >删除
                  </el-button>
                </el-popover>
              </template>
            </el-table-column>
          </el-table>
          <div class="pagination">
            <el-pagination
              v-if="paginations.total > 0"
              :page-size="paginations.pageSize"
              :layout="paginations.layout"
              :total="paginations.total"
              :current-page="paginations.pageIndex"
              @current-change="getCurrRelationshipInstances"
              style="text-align: right"
            >
            </el-pagination>
          </div>
        </div>
      </div>
    </el-main>

    <!--关系实例属性详情展示-->
    <el-dialog
      title="实例属性"
      :visible.sync="isPopup"
      width="800px"
      class="edit"
    >
      <el-form
        ref="currRelationshipInstance"
        :model="currRelationshipInstance.data"
        :rules="currRelationshipInstance.rules"
        label-width="100px"
      >
        <el-form-item label="名称：" prop="名称">
          <el-input
            v-model="currRelationshipInstance.data.type"
            maxlength="20"
            placeholder="请输入名称"
          ></el-input>
        </el-form-item>
        <!-- <el-form-item label="开始节点ID：" prop="开始节点ID">
          <el-input
            type="number"
            v-model.number="currRelationshipInstance.data.startNode"
            maxlength="20"
            placeholder="请输入"
          ></el-input>
        </el-form-item> -->
        <el-form-item label="关系模型：" prop="command">
          <el-select
            v-model="currRelationshipInstance.data.command"
            @change="selectedModel"
            placeholder="请选择"
            clearable
          >
            <el-option
              v-for="item in typelist"
              :key="item.id"
              :label="
                item.start_node_label_name + '->' + item.end_node_label_name
              "
              :value="item.id"
            >
            </el-option>
          </el-select>
          <transition name="el-zoom-in-top">
            <div
              v-show="currRelationshipInstance.data.command ? true : false"
              class="outset"
            >
              <div>
                <popupTree
                  :labels="relationships"
                  TreeType="start"
                  :headerInfo="headerInfo"
                  :editFrom="editFromStart"
                  :isPopup="isPopup"
                  :title="typeTitle"
                  ref="startTable"
                  @handleCurrent="handleCurrent"
                ></popupTree>
              </div>
              <div>
                <popupTreeTwo
                  :labels="relationships"
                  TreeType="end"
                  ref="endTable"
                  :isPopup="isPopup"
                  :title="typeTitle"
                  :editFrom="editFromEnd"
                  :headerInfo="headerInfo"
                  @handleCurrent="handleCurrent"
                ></popupTreeTwo>
              </div>
            </div>
          </transition>
        </el-form-item>
        <!-- <el-form-item label="开始节点：" prop="开始节点名称">
            <el-input
              :disabled="currRelationshipInstance.data.command ? false : true"
              v-model="currRelationshipInstance.data.start_node_data['名称']"
              maxlength="20"
              placeholder="请输入"
              @input="changeVal"
            ></el-input>
        </el-form-item>
        <el-form-item label="结束节点ID：" prop="结束节点ID">
          <el-input
            type="number"
            v-model.number="currRelationshipInstance.data.endNode"
            maxlength="20"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
        <el-form-item label="结束节点：" prop="结束节点名称">
          <el-input
            v-model="currRelationshipInstance.data.end_node_data.名称"
            maxlength="20"
            placeholder="请输入"
          ></el-input>
        </el-form-item> -->
        <!--                <el-form-item label="次数：" prop="次数">-->
        <!--                    <el-input type="number" v-model.number="currRelationshipInstance.data.次数" maxlength="20"-->
        <!--                              placeholder="请输入次数"></el-input>-->
        <!--                </el-form-item>-->
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="isPopup = false">取 消</el-button>
        <el-button type="primary" @click="saveModelInstance">确 定</el-button>
      </span>
    </el-dialog>
  </el-container>
</template>

<!--<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>-->
<script>
import common from "../../../api/common";
import popupTree from "../relationships/components/popupTree";
import popupTreeTwo from "../relationships/components/popupTree";

export default {
  name: "index",
  components: {
    popupTree,
    popupTreeTwo,
  },
  data() {
    return {
      relationships: [],

      paginations: {
        pageIndex: 1, // 当前位于哪页
        pageSize: 10, // 页显示多少条
        total: 0, // 总数
        layout: "total, prev, pager, next", // 翻页属性
      },

      // 选中的模型Id和labelName
      currRelationshipId: 0,
      currRelationshipLabelName: "",

      //当前选中关系的实例列表
      currRelationshipInstances: [],
      //当前选中的实例信息
      currRelationshipInstance: {
        visible: false,
        rules: {
          type: [{ required: true, message: "名称不能为空" }],
          command: [{ required: true, message: "请选择关系模型" }],
          // dataType: [{required: true, message: '数据类型不能为空'}],
          // createDate: [{required: true, message: '创建时间不能为空'}]
        },
        data: {
          start_node_data: {
            名称: "dddd",
          },
          end_node_data: {
            名称: "",
          },
          command: "", //类型
        },
      },
      typelist: [
        {
          start_node_type: 7,
          start_node_lablel_name: "指挥所",
          end_node_type: 14,
          end_node_label_name: "常规潜艇",
          name: "范围一",
        },
      ],
      headerInfo: {},
      editFromEnd: null,
      editFromStart: null,
      isPopup: false,
      typeTitle:"添加"
    };
  },
  methods: {
    init() {
      this.$store.dispatch("ajax", {
        url: "services/app-zonghe/api/dicLabel/tree?type.equals=5",
        method: "get",
        succeed: (res) => {
          this.relationships = res;
        },
      });
    },
    //选中关系
    treeRelationshipClick(data) {
      this.currRelationshipId = data.id;
      this.currRelationshipLabelName = data.label_name;

      this.getCurrRelationshipInstances(1);
    },
    //查询选中关系的实例
    getCurrRelationshipInstances(pageIndex) {
      //获取当前选中模型的实例
      if (pageIndex === undefined) {
        pageIndex = this.paginations.pageIndex;
      } else {
        this.paginations.pageIndex = pageIndex;
      }

      this.$store.dispatch("ajaxEx", {
        url:
          "services/app-zonghe/api/example/cypher/relationships/" +
          this.currRelationshipLabelName,
        method: "get",
        data: { page: pageIndex - 1, size: this.paginations.pageSize },
        succeed: (res) => {
          this.currRelationshipInstances = res.data;
          this.paginations.total = parseInt(res.headers["x-total-count"]);
        },
      });
    },

    //新建关系实例
    addModelInstance() {
      this.currRelationshipInstance.data = {
        id: 0,
        type: this.currRelationshipLabelName,
        startNode: 0,
        endNode: 0,
        start_node_data: {
          名称: "",
        },
        end_node_data: {
          名称: "",
        },
        command: "",
      };
      this.isPopup = true;
      this.editFromStart = null;
      this.editFromEnd = null;
      this.$store.dispatch("ajax", {
        url: `services/app-zonghe/api/relationship/${this.currRelationshipId}/models/`,
        method: "get",
        succeed: (res) => {
          console.log(res);
          this.typelist = res;
          this.typeTitle="添加";
        },
      });
    },
    //编辑关系实例
    showOrEdit(row) {
      console.log(row)
      this.currRelationshipInstance.data = common.clone(row);
      this.editFromStart = common.clone(row.end_node_data);
      this.editFromEnd = common.clone(row.start_node_data);
      // console.log(
      //   "show or edit instance ................. ",
      //   this.currRelationshipInstance.data
      // );
      this.$store.dispatch("ajax", {
        url: `services/app-zonghe/api/relationship/${this.currRelationshipId}/models/`,
        method: "get",
        succeed: (res) => {
          console.log(res);
          this.typelist = res;
          this.isPopup = true;
          this.typeTitle="编辑";
          setTimeout(()=>{
            this.$refs.startTable.initData();
            this.$refs.endTable.initData();
          })
          
          this.typelist.forEach((res) => {
            if (res.id == this.currRelationshipInstance.data.command) {
              this.headerInfo = res;
            }
          });
        },
      });
    },
    //删除关系实例
    delInstance(row) {
      console.log(
        "del instance ................. ",
        row,
        this.currRelationshipLabelName
      );
      // this.delPopoverClose('del_popover_'+row.id);
      this.$store.dispatch("ajax", {
        url:
          "services/app-zonghe/api/example/cypher/relationships/" +
          this.currRelationshipLabelName +
          "/" +
          row.id,
        method: "delete",
        data: {},
        succeed: () => {
          this.getCurrRelationshipInstances();
          this.$message.success("删除成功");
          this.delPopoverClose("del_popover_" + row.id);
        },
      });
    },
    //新增或修改关系实例
    saveModelInstance() {
      let _this = this;
      this.$refs.currRelationshipInstance.validate((valid) => {
        console.log(valid);
        let obj = {};
        obj.isStart = false;
        obj.isEnd = false;
        if (valid) {
          _this.$refs.startTable.$refs.miniDragon.validate((author) => {
            if (author) {
              obj.isStart = author;
            }
          });
          _this.$refs.endTable.$refs.miniDragon.validate((ate) => {
            if (ate) {
              obj.isEnd = ate;
            }
          });
          if (obj.isStart && obj.isEnd) {
            if (this.currRelationshipInstance.data.id === 0) {
              //创建关系 创建语句不一样 需要修改body的格式
              let currData = common.clone(this.currRelationshipInstance.data);
              delete currData["start_node_data"];
              delete currData["startNode"];
              delete currData["end_node_data"];
              delete currData["endNode"];

              let whereJson = {
                where: {
                  bool_and: [
                    {
                      "a.id.equals": this.currRelationshipInstance.data
                        .startNode,
                    },
                    {
                      "b.id.equals": this.currRelationshipInstance.data.endNode,
                    },
                  ],
                },
              };
              let newData = {};
              Object.assign(newData, currData, whereJson);
              this.$store.dispatch("ajax", {
                url:
                  "services/app-zonghe/api/example/cypher/relationships/" +
                  this.currRelationshipLabelName,
                method: "post",
                data: newData,
                succeed: () => {
                  this.getCurrRelationshipInstances();
                  this.$message.success("保存成功");
                  this.isPopup = false;
                  this.$refs.currRelationshipInstance.resetFields();
                },
              });
            } else {
              //更新 需要去除 startNodeData和endNodeData
              //不能直接去除，直接去除vue会认为this.currRelationshipInstance.data下没有startNodeData、endNodeData两个子map，页面会报错
              let currData = common.clone(this.currRelationshipInstance.data);
              delete currData["start_node_data"];
              delete currData["end_node_data"];
              console.log("dddddddddddddddddddddd", currData);

              //对于关系只能更新其普通属性 startNode和endNode无法像普通属性那样更新 目前暂时不提供修改的功能
              this.$store.dispatch("ajax", {
                url:
                  "services/app-zonghe/api/example/cypher/relationships/" +
                  this.currRelationshipLabelName,
                method: "put",
                data: currData,
                succeed: () => {
                  this.getCurrRelationshipInstances();
                  this.$message.success("保存成功");
                  this.isPopup = false;
                  this.$refs.currRelationshipInstance.resetFields();
                },
              });
            }
          }
        }
      });
    },

    delPopoverShow(ref) {
      this.$refs[ref].doShow();
    },
    delPopoverClose(ref) {
      this.$refs[ref].doClose();
    },
    //选择 -开始节点和结束节点
    handleCurrent(data, type) {
      console.log(type);
      console.log(data);
      if (type == "start") {
        this.currRelationshipInstance.data.start_node_data["名称"] = data["名称"];
        this.currRelationshipInstance.data.startNode = data.id;
      } else {
        this.currRelationshipInstance.data.end_node_data.名称 = data["名称"];
        this.currRelationshipInstance.data.endNode = data.id;
      }
    },
    changeVal(val) {
      console.log(val);
    },
    //选择模型
    selectedModel(id) {
      this.typelist.forEach((res) => {
        if (res.id == id) {
          console.log(res);
          this.headerInfo = res;
        }
      });
    },
  },
  mounted() {
    this.init();
  },
};
</script>
<style scoped>
.outset {
  display: flex;
  flex-flow: row nowrap;
  justify-content: space-around;
  align-items: center;
  border: 1px solid #ccc;
  box-shadow: 0px 0px 5px #ccc;
  border-radius: 5px;
  padding: 5px;
  margin-top: 6px;
}
</style>
